﻿using Newtonsoft.Json;
using PMRC.API.Model.WeChat;
using System.Net;

namespace PMRC.API.Helper
{
    /// <summary>
    /// 微信帮助类
    /// </summary>
    public static class WeChatHelpr
    {
        /// <summary>
        /// 微信获取访问令牌的API地址
        /// </summary>
        private readonly static string _accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";

        /// <summary>
        /// 根据授权码获取访问令牌
        /// </summary>
        /// <param name="appId">应用ID</param>
        /// <param name="appSecret">应用密钥</param>
        /// <param name="code">授权码</param>
        /// <returns>访问令牌信息</returns>
        public static async Task<string> GetAccessToken(string appId, string appSecret, string code)
        {
            string url = string.Format(_accessTokenUrl, appId, appSecret, code);
            // 发起HTTP请求，获取访问令牌
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                
                return responseBody;
            }
        }
    }
}
